'use strict';

/* Controllers */
app.controller('houseOwnerListCtl', function($scope, $http, rest, $compile, $location, ngDialog, user, $state, $window, uiLoad, $rootScope, $ocLazyLoad) {
  var token = $window.localStorage.getItem("token");
  
  //自定义方法状态数据
	$scope.methodsStatus = [
	        {
	            "menuType" : "AVAILABLE",
	            "name" : "可用"
	        },
	        {
	            "menuType" : "FORBID",
	            "name" : "禁止"
	        },
	        {
	            "menuType" : "DELETE",
	            "name" : "删除"
	        },
	   		{
	            "menuType" : "",
	            "name" : "全部"
	        }
	    ];
	$scope.itemStatus = $scope.methodsStatus[0]; //默认为可用
	
	//方法级权限
	var accessStr = $window.localStorage.getItem("accessStr");
	$scope.btns = {
		add: 'innjia',  //新建
		delete: 'innjia',  //删除
		edit: 'innjia',  //编辑
		jurisdiction: 'innjia',  //权限分配
		resetPasswords: 'innjia',  //重置密码
		addmember: 'innjia',  //添加成员
		exportExcel: 'innjia', //导出表格
		batchExportImg: 'innjia',  //批量导出图片
		details: 'innjia',  //详情
		rent: 'innjia',  //租赁PDF
		list: 'innjia'  //列表
	}
	//延迟执行 - 当左侧菜单生产完毕再获取当前菜单的ID 利用ui-sref-active有且只有一个active即当前的特性用jq去获取预先存储在菜单上的id
	user.response().then(function(res){
		var nowId = $(document).find(".navItem.active").attr("data-id");
		rest.decoJava({
		   	 type: "post",
		     url: "/tenancy-sys/admin/menu/detail/"+nowId,
		     data: "",
		     //contentType:"application/json",
		     beforeSend: function(request){
				request.setRequestHeader("token", token); 
			},
		    success: function(data){ 
		    	console.log(data)
			    if(data.code == "0000"){
				    //匹配权限
				    angular.forEach(data.result.menuMethods,function(data){
				    	if(data.methodTagName == "add"){
				    		$scope.btns.add = data.id;
				    	} else if(data.methodTagName == "delete"){
				    		$scope.btns.delete = data.id;
				    	} else if(data.methodTagName == "edit"){
				    		$scope.btns.edit = data.id;
				    	} else if(data.methodTagName == "jurisdiction"){
				    		$scope.btns.jurisdiction = data.id;
				    	} else if(data.methodTagName == "resetPasswords"){
				    		$scope.btns.resetPasswords = data.id;
				    	} else if(data.methodTagName == "addmember"){
				    		$scope.btns.addmember = data.id;
				    	} else if(data.methodTagName == "exportExcel"){
				    		$scope.btns.exportExcel = data.id;
				    	} else if(data.methodTagName == "batchExportImg"){
				    		$scope.btns.batchExportImg = data.id;
				    	} else if(data.methodTagName == "details"){
				    		$scope.btns.details = data.id;
				    	} else if(data.methodTagName == "rent"){
				    		$scope.btns.rent = data.id;
				    	} else if(data.methodTagName == "list"){
				    		$scope.btns.list = data.id;
				    	}
				    })
			    } else if(data.message == "菜单Id有误！！！"){
			    	// $window.location.reload();
			    } else{
			    	layer.msg(data.message+'请刷新试试', {
			        	offset:'t',
			        	icon: 2
					});
			    }
		    }
	    });
	
	})
  
  var tabHeight = ($window.innerHeight - 268) + "px"; //table内容区高度
  $scope.dataTableSettings = {
    "sAjaxSource": "/tenancy-sys/admin/menuMethod/list",
    // "dom": "tipr",
    "bFilter": true, //搜索
    "sScrollY": tabHeight, //给定高度，内容超出即出滚动条
    "bScrollCollapse": false, //不管内容多少高度固定
    "aLengthMenu": [25, 50, 100, 200],
    "iDisplayLength": 25,
    "sDom": '<"top">rt<"bottom"lip><"clear">', //位置 l-每页显示数量,f-过滤输入,t-表单Table,i-信息,p-翻页
    "bAutoWidth": true,  //自适应列宽
    "aoColumns": [{
      "mDataProp": "",
      "sDefaultContent": "",
      "sClass": "center handle-ck"
    }, {
      "mDataProp": "methodName",
      "sTitle": "方法名称",
      "sDefaultContent": "",
      "sClass": "center"
    }, {
      "mDataProp": "menuName",
      "sTitle": "所属菜单",
      "sDefaultContent": "",
      "sClass": "center failure handle-upMenu"
    }, {
      "mDataProp": "methodTagName",
      "sTitle": "关键字",
      "sDefaultContent": "",
      "sClass": "center failure handle-upMenu"
    }, {
      "mDataProp": "",
      "sTitle": "方法状态",
      "sDefaultContent": "",
      "sClass": "center menuStatus"
    }, {
      "mDataProp": "createTime",
      "sTitle": "创建时间",
      "sDefaultContent": "",
      "sClass": "center"
    }, {
      "mDataProp": "remark",
      "sTitle": "方法备注",
      "sDefaultContent": "",
      "sClass": "center"
    }, {
      "mDataProp": "operate",
      "sTitle": "操作",
      "sDefaultContent": "",
      "sClass": "center handle-td"
    }],
    "fnRowCallback": function(nRow, aData, iDisplayIndex) {
      var btnStr = "";

      btnStr += "<button type='button' class='btn-yellow' style='margin-right:10px;' data-btn='btns.edit' ng-click='edit(\"" + iDisplayIndex + "\",$event)'>编辑</button>";
      $(nRow).find(".handle-td").append($compile(btnStr)($scope));

      var checkStr = "";
      checkStr += '<input type="checkbox" data-index="' + iDisplayIndex + '" value="' + $scope.myDatas.result[iDisplayIndex].id + '" class="checkchild" />';
      $(nRow).find(".handle-ck").append($compile(checkStr)($scope));

      //菜单状态
	    var menuStatus = "";
	    if(aData.status == "AVAILABLE"){
	    	menuStatus = "可用";
	    } else if(aData.status == "DELETE"){
	    	menuStatus = "删除";
	    } else if(aData.status == "FORBID"){
	    	menuStatus = "禁止";
	    }
	    $(nRow).find(".menuStatus").append(menuStatus);
    },
    "fnDrawCallback": function(oSettings) {

    },
    "fnServerParams": function(aoData) {

    },
    "fnServerData": function(sSource, aData, fnCallback, dataTableObject) {
      //自定义给datatables传递的参数
      var obj = dataTableObject.oAjaxData,
        _baseParams = {
          'page': obj.iDisplayStart / obj.iDisplayLength + 1,
          'rows': obj.iDisplayLength,
          'search': 'false',
          'nd': '1494221804416',
          // 'rows': 50,
          // 'page': 1,
          'order': "asc",
          "methodName": $scope.menuName,
          'status': $scope.itemStatus.menuType
        };

      var __data = angular.extend({}, _baseParams, obj.queryParams);
      rest.decoJava({
        type: "post",
        url: sSource,
        data: __data,
        beforeSend: function(request) {
          request.setRequestHeader("token", token);
        },
        success: function(data) {
          $scope.myDatas = data;
          var data1 = {
            'aaData': data.result,
            'sEcho': obj.sEcho,
            'iTotalDisplayRecords': data.pager.recordCount,
            'iTotalRecords': data.records,
          };
          fnCallback(data1);
          //$(dataTableObject.nScrollBody).css('overflow', 'visible');
        	//$(dataTableObject.nScrollBody).css('margin-bottom', 60 + 'px');
        	$(".dataTables_scroll").css("overflow", "auto");
					$(".dataTables_scrollBody").css("overflow", "visible");
        }
      });

      //搜索 说明 只要是点击的搜索就让page为1 并且刷新datatables目的是回到第一页
      //说明 自定义搜索只需在点击搜索的时候改变下datatables传过去的参数 然后$scope.dataTable.fnClearTable()即可
      $scope.search = function() {
        __data.page = 1;
        $scope.dataTable.fnClearTable();
      }

    }
  }

  $scope.initFinish = function(dataTable) {
    $scope.dataTable = dataTable;
  }

  //全部选中和取消
  $scope.allMenu = function(e) {
    var This = angular.element(e.target);
    if (This.is(":checked")) {
      angular.element(".checkchild").prop("checked", true);
    } else {
      angular.element(".checkchild").prop("checked", false);
    }
  }

  //修改
  $scope.edit = function(iDisplayIndex, e) {
  	
  	//权限控制
		var nowId = this.btns.edit;
		if(accessStr.indexOf(nowId) == -1){
			layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
		}
  	
    //var btn = $(e.target);
    ngDialog.openConfirm({
      template: 'js/module/decorate/listEdit.html',
      resolve: {
        load: function() {
          return $ocLazyLoad.load('angularFileUpload').then(
            function() {
              return uiLoad.load(['js/module/decorate/listEdit.js'])
            });
        }
      },
      data: $scope.myDatas.result[iDisplayIndex],
      scope: $scope,
      width: 1200,
      // height: 700
    }).then(function(data) {
      $scope.dataTable.fnClearTable();
    }, function(reason) {
      $scope.dataTable.fnClearTable();
    });

  }

  //新建方法
  $scope.newFn = function(iDisplayIndex, e) {
  	
  	//权限控制
		var nowId = this.btns.add;
		if(accessStr.indexOf(nowId) == -1){
			layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
		}
  	
    ngDialog.openConfirm({
      template: 'js/module/decorate/newFn.html',
      resolve: {
        load: function() {
          return $ocLazyLoad.load('angularFileUpload').then(
            function() {
              return uiLoad.load(['js/module/decorate/newFn.js'])
            });
        }
      },
      data: "",
      scope: $scope,
      width: 1200,
      // height: 700
    }).then(function(data) {
      $scope.dataTable.fnClearTable();
    }, function(reason) {
      $scope.dataTable.fnClearTable();
    });
  }

  //删除方法
  $scope.deleteFn = function(e) {
  	
  	//权限控制
		var nowId = this.btns.delete;
		if(accessStr.indexOf(nowId) == -1){
			layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
		}
  	
    if ($(".checkchild:checked").length == 0) {
      layer.msg("没有选中项", {
        offset: 't',
        icon: 2,
        time: 2000
      });
    } else {
      layer.msg("确定删除吗？", {
        offset: 't',
        icon: 3,
        time: 0, //不自动关闭
        btn: ['确定', '取消'],
        yes: function(index) {
          layer.close(index);
          //执行删除 数据格式要求 要将数组转换成字符串 并截除最后的逗号
          var idArr = [];
          $(".checkchild").each(function() {
            if ($(this).is(":checked")) {
              idArr.push($(this).val());
            }
          });
          var _idstring = "";
          angular.forEach(idArr, function(data) {
            _idstring += data + ',';
          })
          var _idstring = _idstring.substring(0, _idstring.length - 1);

          rest.decoJava({
            url: '/tenancy-sys/admin/menuMethod/batch/delete',
            data: {
              "ids": _idstring
            },
            beforeSend: function(request) {
              request.setRequestHeader("token", token);
            },
            success: function(result) {
              if (result.code == "0000") {
                layer.msg(result.message, {
                  offset: 't',
                  icon: 1,
                  time: 0, //不自动关闭
                  btn: ['确定'],
                  yes: function(index) {
                    layer.close(index);
                    $scope.dataTable.fnClearTable();
                  }
                });
              } else {
                layer.msg(result.message, {
                  offset: 't',
                  icon: 5,
                  time: 0, //不自动关闭
                  btn: ['确定'],
                  yes: function(index) {
                    layer.close(index);
                  }
                });
              }
            }
          });
        }
      });
    }
  };

  //顶部编辑
  $scope.fnEditTop = function() {
  	
  	//权限控制
		var nowId = this.btns.edit;
		if(accessStr.indexOf(nowId) == -1){
			layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
		}
  	
    if ($(".checkchild:checked").length == 0) {
      layer.msg("没有选中项", {
        offset: 't',
        icon: 2,
        time: 2000
      });
    } else if ($(".checkchild:checked").length >= 2) {
      layer.msg("一次只能编辑一项", {
        offset: 't',
        icon: 2,
        time: 2000
      });
    } else {
      var iDisplayIndex = parseInt($(".checkchild:checked").attr("data-index"));
      console.log(typeof iDisplayIndex);
      $scope.edit(iDisplayIndex)
    }
  }

});